//
//  HMEmoticonTools.swift
//  Black22
//
//  Created by Apple on 16/11/26.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import YYModel
//  每页显示20个表情
let NumberOfPage = 20
//  最近表情归档和解档路径
let RecentPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticon.archiver")
//  表情图片专用类
class HMEmoticonTools: NSObject {
    //  单例全局访问点
    static let sharedTools: HMEmoticonTools = HMEmoticonTools()
    //  构造函数私有化
    override init() {
        super.init()
        
        print(normalEmoticonArray.count)
        print(emojiEmoticonArray.count)
        print(lxhEmoticonArray.count)
        
    }
    
    //  创建表情bundle对象
    lazy var emoticonBundle: Bundle = {
        //  bundle路径
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        //  根据路径创建bundle
        let bundle = Bundle(path: path)!
        return bundle
    }()
    
    //  默认表情
    private lazy var normalEmoticonArray: [HMEmoticon] = {
    
        return self.loadPlistData(folderName: "default", fileName: "info.plist")
        
    }()
    
    //  默认表情
    private lazy var emojiEmoticonArray: [HMEmoticon] = {
        
        return self.loadPlistData(folderName: "emoji", fileName: "info.plist")
        
    }()
    
    //  默认表情
    private lazy var lxhEmoticonArray: [HMEmoticon] = {
        
        return self.loadPlistData(folderName: "lxh", fileName: "info.plist")
        
    }()
    
    //  最近表情
    private lazy var recentEmoticonArray: [HMEmoticon] = {
        //  有本地最近表情返回，否则返回空数组
        if let localArray = self.loadRecentEmoticonArray() {
            return localArray
        } else {
            
            let array = [HMEmoticon]()
            return array
        }
        
    }()
    
    //  表情视图所需要的数据源
    lazy var allEmoticonArray: [[[HMEmoticon]]] = {
    
        return [
            [self.recentEmoticonArray],
            self.sectionEmoticonsWithArray(emoticions: self.normalEmoticonArray),
            self.sectionEmoticonsWithArray(emoticions: self.emojiEmoticonArray),
            self.sectionEmoticonsWithArray(emoticions: self.lxhEmoticonArray)
        ]
    }()
    
    
    //  每组数据分钟几页显示组成二维数组
    func sectionEmoticonsWithArray(emoticions: [HMEmoticon]) -> [[HMEmoticon]] {
        let pageCount = (emoticions.count - 1) / NumberOfPage + 1
        //  遍历页数，拆分数组
        var tempArray = [[HMEmoticon]]()
        for i in 0..<pageCount {
            let loc = i * NumberOfPage
            var len = NumberOfPage
            if loc + len > emoticions.count {
                //  截取剩余的个数
                len = emoticions.count - loc
            }
            
            let subArray = (emoticions as NSArray).subarray(with: NSMakeRange(loc, len)) as! [HMEmoticon]
            tempArray.append(subArray)
        }
        return tempArray
    }
    
    
    //  根据文件夹名和文件名获取plist数据
    private func loadPlistData(folderName: String, fileName: String) -> [HMEmoticon] {
        let subPath = folderName + "/" + fileName
        
        let path = self.emoticonBundle.path(forResource: subPath, ofType: nil)!
        
        //  根据路径加载数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        
        //  字典转模型
        let modleArray = NSArray.yy_modelArray(with: HMEmoticon.self, json: dicArray) as! [HMEmoticon]
        
        //  拼接图片路径
        for model in modleArray {
            if model.type == "0" {
                let path = self.emoticonBundle.path(forResource: folderName, ofType: nil)! + "/" + model.png!
                model.fullPath = path
                model.folderName = folderName
                
            }
        }
        
        return modleArray
    
    }
    
    //  解档最近表情
    func loadRecentEmoticonArray() -> [HMEmoticon]? {
        let recentArray = NSKeyedUnarchiver.unarchiveObject(withFile: RecentPath) as? [HMEmoticon]
        return recentArray
    }
    
    //  保存最近表情
    func saveRecentEmoticonArray(emoticon: HMEmoticon) {
        //  判断表情是否之前存在过，如果存在过删除
        for (i, etn) in self.recentEmoticonArray.enumerated() {
            if emoticon.type == "0" {
                //  图片，比较表情描述
                if etn.chs == emoticon.chs {
                    //  删除对应的元素
                    recentEmoticonArray.remove(at: i)
                    break
                }
            } else {
                //  emoji
                if etn.code == emoticon.code {
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }
            
        }
        //  把点击的表情插入数组的第一个元素的位置
        self.recentEmoticonArray.insert(emoticon, at: 0)
        //  如果最近表情超过20个表情，删除最后一个表情元素
        while self.recentEmoticonArray.count > 20 {
            //  删除最后一个元素
            recentEmoticonArray.removeLast()
        }
        //  更新数据
        allEmoticonArray[0][0] = self.recentEmoticonArray
        //  归档数据
        NSKeyedArchiver.archiveRootObject(self.recentEmoticonArray, toFile: RecentPath)
    }
    
    
    //  根据表情描述查找表情模型
    func selectEmoticon(chs: String) -> HMEmoticon? {
        //  图片表情查找，默认数组和浪小花数组
        for emoticon in self.normalEmoticonArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        
        for emoticon in self.lxhEmoticonArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        
        return nil
        
    }
    
    
    
}
